<?php


#验证密钥
require_once 'check-key-word.php';
require_once './public/lkw.php';
require_once 'variable.php';
// require_once './public/pdf-to-img.php';

$imagePath = $_POST['imagePath'];

if (!$imagePath) {
	$imagePath='';
}

// 如果是pdf文件
if(stristr($imagePath, 'pdf')){
	$md5 = md5($imagePath);
	$cachePath = $cache.'/'.$md5;

	# 有缓存信息的 直接加载缓存信息返回
	if(is_dir($cachePath)){
		$request = array(
			'type'=>'pdf',
			'list'=>get_file_list($cachePath),
			'msg'=>'already have conversion file',
		);

	}else{
		# 通过异步的post请求 触发pdf的转换
		$command = 'php ./tool/pdf-to-img.php "'.$imagePath.'" "'.$md5.'" "'.$servePath.'"';

		pclose(popen('nohup '.$command.' & 2>&1','r'));

		# 返回暂无图片的信息
		$request = array(
			'type'=>'pdf',
			'target'=>$md5,
			'msg'=>"pdf file conversion in progress",
			'command'=>$command,
		);
	}
	
}else{
	$request = array(
		'type'=>'img',
		'list'=>get_file_list($imagePath),
		'msg'=>'images list load success',
	);
}

#返回信息
echo json_encode($request);

function get_file_list($path){
	$list = array();
	$dir = dir($path);

	while (($file = $dir->read()) !== false){
		// 排除目录
		if($file=='.'||$file=='..') continue;

		$route = $path."/".$file;
		if(is_img($route)) array_push($list,$route);
	}

	$dir->close();

	sort($list,SORT_NATURAL | SORT_FLAG_CASE);

	return $list;
}

function file_exist_md5($fileName,$fileList){

	foreach ($fileList as $key => $value) {

		if($value['md5']===md5_file($fileName)) return $value['name'];
	}

	return false;
}

function file_exist_name($fileName,$fileList){
	global $SAMEFILENAME;

	$prefix = $SAMEFILENAME===0 ? '' : '('.$SAMEFILENAME.')';
	$finalName = $prefix.$fileName;

	foreach ($fileList as $key => $value) {
		if($value['name']===$finalName){
			$SAMEFILENAME++;
			return file_exist_name($fileName);
		}	
	}

	$SAMEFILENAME=0;
	return $finalName;
}

?>